package ua.kharkov.khpi.tarasenko.bach.dao.mysql.usersession;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.db.EShopDataStoreException;
import ua.kharkov.khpi.tarasenko.bach.core.logging.CustomerSession;
import ua.kharkov.khpi.tarasenko.bach.core.utils.SessionUtils;
import ua.kharkov.khpi.tarasenko.bach.dao.core.usersession.UserSessionDAO;

public class UserSessionDAOImpl implements UserSessionDAO {

	private static final String TABLE_SESSION = "SESSION";

	private static final String QUERY_SAVE_SESSION = "INSERT INTO "
			+ TABLE_SESSION
			+ "(USER_ID, START_DATE, ACCESS_SEQUENCE) VALUES(?, ?, ?)";
	private static final String QUERY_GET_SESSIONS = "SELECT SESSION_ID, USER_ID, START_DATE, ACCESS_SEQUENCE FROM "
			+ TABLE_SESSION;

	private Connection conn;

	public UserSessionDAOImpl(Connection conn) {
		this.conn = conn;
	}

	@Override
	public void saveSession(CustomerSession session)
			throws EShopDataStoreException {

		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(QUERY_SAVE_SESSION);
			if (session.getUserId() < 1) {
				ps.setInt(1, 1);								
			} else {
				ps.setInt(1, session.getUserId());				
			}

			if (session.getSessionStartDate() == null) {
				ps.setTimestamp(2, java.sql.Timestamp.valueOf("1992-02-02 00:00:00"));
			} else {
				ps.setTimestamp(2, new java.sql.Timestamp(session
						.getSessionStartDate().getTime()));				
			}
			ps.setString(3, SessionUtils.transactionToString(session));

			ps.executeUpdate();
		} catch (SQLException e) {
			throw new EShopDataStoreException(
					"Error occurred during saving session", e);
		} finally {
			DBUtils.close(null, ps);
		}
	}

	@Override
	public List<CustomerSession> getAllSessions()
			throws EShopDataStoreException {

		ArrayList<CustomerSession> session = new ArrayList<CustomerSession>();
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = conn.prepareStatement(QUERY_GET_SESSIONS);

			rs = ps.executeQuery();
			CustomerSession customerSession = null;
			while (rs.next()) {
				customerSession = new CustomerSession();
				customerSession.setSessionId(rs.getInt("SESSION_ID"));
				customerSession.setUserId(rs.getInt("USER_ID"));
				customerSession
						.setSessionStartDate(DBUtils
								.convertSqlDateToUtilDate(rs
										.getTimestamp("START_DATE")));
				customerSession.setTransactions(SessionUtils
						.parseTransactions(rs.getString("ACCESS_SEQUENCE")));
				session.add(customerSession);
			}
		} catch (SQLException e) {
			throw new EShopDataStoreException(
					"Error occurred during getting all sessions.", e);
		} finally {
			DBUtils.close(rs, ps);
		}
		return session;
	}
}
